<template>
    <div class="title">
        课件查看
    </div>
    <div class="option">
        <span>选择课程：</span>
        <el-select
            v-model="course"
            :empty-values="[null, undefined]"
            :value-on-clear="null"
            placeholder="Select"
            style="width: 240px"
            @change="(val: any) => selectionChange(val)"
        >
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
        </el-select>
        <span style="margin-left: 20px">文件名：</span>
        <el-input v-model="inputFileName" style="width: 240px"/>
        <span style="margin-left: 20px">上传时间：</span>
        <div class="date-picker">
            <el-date-picker
                v-model="date"
                type="date"
                placeholder="选择日期"
                :size="'default'"
            />
        </div>
    </div>
    <div class="table">
        <el-table
            :data="tableData"
            style="width: 100%; margin-bottom: 20px"
            row-key="date"
            border
            :size="pageSize"
            type="expand"
            @cell-click="handleCellClick"
        
        >
            <el-table-column prop="fileName" label="文件名" sortable>
                <template #default="scope">
                    <span>
                        <img style="width: 20px;height: 20px" :src="getFileIcon(scope.row.fileName)" alt="">
                        {{ scope.row.fileName }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="fileSize" label="文件大小" sortable/>
            <el-table-column prop="date" label="上传日期" sortable/>
            <el-table-column prop="courseName" label="课程名称" sortable/>
            <el-table-column prop="teacherName" label="授课教师" sortable/>
            <el-table-column>
                <template #default="scope">
                    <template v-if="scope.row.fileSize == ''">
                    </template>
                    <template v-else>
                        <el-button type="primary" size="small"
                                   @click="handleDownload(scope.row.p_path,scope.row.fileName,scope.row.courseName)">下载
                        </el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="[10,20, 50, 100, 400]"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 20px; justify-content: center"
            v-bind:total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {getStudentCourseWare, getStudentCourseWareView} from "@/service/student/student.service";
import {timestampToDate} from "@/util/time.utils";

const course = ref('')
const date = ref('')
const options = ref([
    {
        value: '',
        label: '全部',
    }])
const inputFileName = ref('')
const selection = ref('')
// 文件目录列表，文件目录名，上传日期，课程名称，父目录，
const filePathList = ref([{}])
// 文件列表，属性：文件名，文件大小，上传日期，课程名称，授课教师，最近的父目录
const fileList = ref([])
// 分页大小
const pageSize = ref(20)
// 页码
const page = ref(1)
const total = ref(10)
const tableData = ref([{
    fileName: "",
    fileSize: "",
    date: "",
    courseName: "",
    teacherName: "",
}])

onMounted(() => {
    getStudentCourseWareView((data: any) => {
        console.log(data)
        // 获取课程数据
        for (const course of data.studentCourseInfoDto.studentCourseList) {
            options.value.push({
                value: course.courseId,
                label: course.name,
            })
        }
        // 读取文件和目录
        getFilePath(data.fileList, data.pathList)
    })
})

/**
 * 选择课程
 * @param val
 */
function selectionChange(val: any) {
    selection.value = val
}

/**
 * 根据课程/文件名/日期查询课件
 */
function handleSearch() {
    let fileName: any
    let date1: any
    let courseId: any
    if (inputFileName.value == '') {
        fileName = null
    } else {
        fileName = inputFileName.value
    }
    if (date.value == '') {
        date1 = null
    } else {
        date1 = date.value
    }
    if (course.value == '') {
        courseId = null
    } else {
        courseId = course.value
    }
}


/**
 * 当pageSize发生变化
 */
const handleSizeChange = (size: number) => {
    pageSize.value = size
}

/**
 * 当页码发生变化
 *
 */
const handleCurrentChange = (num: number) => {
    page.value = num
}

/**
 * 获取表格数据，文件和目录的树形结构
 * @param files
 * @param paths
 */
function getFilePath(files: any, paths: any) {
    tableData.value = []
    try {
        for (const file of files) {
            let p_path = file.parentPath
            let isAtRoot = false
            try {
                for (const op of options.value) {
                    // 判断是否在根目录
                    if (op.value === p_path) {
                        isAtRoot = true
                        tableData.value.push({
                            fileName: file.fileName,
                            fileSize: file.fileSize + "KB",
                            date: timestampToDate(String(Number(file.date) / 1000)),
                            courseName: file.courseName,
                            teacherName: file.teacherName,
                            p_path: ""
                        })
                    }
                }
            } catch (err) {
            }
        }
    } catch (err) {
    }
    try {
        for (const path of paths) {
            let p_path = path.parentPath
            let isAtRoot = false
            for (const op of options.value) {
                // 判断是否在根目录
                if (op.value === p_path) {
                    isAtRoot = true
                    // 获取子目录和目录下文件
                    let full_path = ""
                    let childrens = getSubFilePath(full_path, path.pathName, files, paths)
                    if (childrens.length > 0) {
                        tableData.value.push({
                            fileName: path.pathName,
                            fileSize: "",
                            date: timestampToDate(String(Number(path.date) / 1000)),
                            courseName: path.courseName,
                            p_path: "",
                            children: childrens
                        })
                    } else {
                        tableData.value.push({
                            fileName: path.pathName,
                            fileSize: "",
                            date: timestampToDate(String(Number(path.date) / 1000)),
                            courseName: path.courseName,
                            p_path: "",
                        })
                    }
                }
            }
        }
    } catch (err) {
    }
}

/**
 * 获取目录文件和子目录
 * @param full_path
 * @param parentPath 父目录
 * @param files
 * @param paths
 */
function getSubFilePath(full_path: any, parentPath: any, files: any, paths: any) {
    let children = []
    try {
        for (const file of files) {
            let p_path = file.parentPath
            // 判断是否在这个父目录
            if (parentPath === p_path) {
                children.push({
                    fileName: file.fileName,
                    fileSize: file.fileSize + "KB",
                    date: timestampToDate(file.date),
                    courseName: file.courseName,
                    teacherName: file.teacherName,
                    p_path: full_path + "/" + p_path
                })
            }
        }
    } catch (err) {
    }
    try {
        for (const path of paths) {
            let p_path = path.parentPath
            // 判断是否在这个父目录
            if (parentPath === p_path) {
                // 获取子目录和目录下文件
                let childrens = getSubFilePath(full_path + "/" + p_path, path.pathName, files, paths)
                if (childrens.length > 0) {
                    children.push({
                        fileName: path.pathName,
                        fileSize: "",
                        date: timestampToDate(path.date),
                        courseName: path.courseName,
                        p_path: full_path + "/" + p_path,
                        children: childrens
                    })
                } else {
                    children.push({
                        fileName: path.pathName,
                        fileSize: "",
                        date: timestampToDate(path.date),
                        courseName: path.courseName,
                        p_path: full_path + "/" + p_path
                    })
                }
                
            }
        }
    } catch (err) {
        console.log(err)
    }
    return children
}

/**
 * 根据文件后缀返回svg
 * @param fileName
 */
function getFileIcon(fileName: any) {
    console.log(fileName)
    
    if (!fileName.includes('.')) {
        return "/src/assets/svg/folder.svg"
    }
    const extension = fileName.split('.').pop().toLowerCase();
    switch (extension) {
        case 'pdf':
            return '/src/assets/svg/pdf.svg';
        case 'doc':
        case 'docx':
            return '/src/assets/svg/word.svg';
        case 'xls':
        case 'xlsx':
            return "/src/assets/svg/excel.svg"
        case 'ppt':
        case 'pptx':
            return '/src/assets/svg/ppt.svg';
        case 'jpg':
        case 'jpeg':
            return '/src/assets/svg/jpg.svg';
        case 'png':
            return '/src/assets/svg/png.svg';
        case 'gif':
            return '/src/assets/svg/gif.svg';
        case 'mp4':
        case 'avi':
            return '/src/assets/svg/mp4.svg';
        case 'mp3':
        case 'wav':
            return '/src/assets/svg/mp3.svg';
        default:
            return '/src/assets/svg/file.svg';
    }
}

function handleCellClick(row: any, column: any, element: any) {

}

/**
 * 下载文件
 * @param path
 * @param fileName
 * @param courseName
 */
function handleDownload(path: any, fileName: any, courseName: any) {
    let courseId = ''
    // 获取courseId
    for (const op of options.value) {
        if (op.label == courseName) {
            courseId = op.value
        }
    }
    getStudentCourseWare(courseId, path, fileName, () => {
    })
}
</script>


<style scoped>
.date-picker {
    display: inline;
}

.title {
    font-size: 20px;
    margin-bottom: 10px;
}

.option {
    margin-bottom: 20px;
}
</style>